package com.zx;

import com.zx.annotations.Service;
import com.zx.dao.AccountDao;
import com.zx.dao.impl.JdbcAccountDaoImpl;
import com.zx.factory.BeanDefinition;
import com.zx.factory.BeanDefinitionFactory;
import com.zx.factory.RegisterBean;
import com.zx.service.TransferService;
import com.zx.servlet.TransferServlet;
import com.zx.utils.ClassUtil;
import com.zx.utils.DruidUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: iocaop
 * @Package: com.zx
 * @ClassName: MyBeanFactory
 * @Author: 1
 * @Description: 1
 * @Date: 2021/9/16 1:42
 */
public class MyApplicationContext{

    private final static String PACKAGE_NAME = "com.zx";

    private final static Map<String,Object> map = new HashMap<>();  // 存储对象

    private final  static  List<BeanDefinition> beanDefinitionList = new ArrayList<>();

    static {
        //扫描全包获取当前包下所有的类
        List<Class<?>> classes = ClassUtil.getClasses(PACKAGE_NAME);

        for ( Class c:classes
             ) {
            //判断是否存在注解
            if(needInit(c.getAnnotations())){
                BeanDefinition beanDefinition = BeanDefinitionFactory.buildBeanDefinition(c);
                beanDefinitionList.add(beanDefinition);
            }
        }
        //注册bean
        RegisterBean registerBean = new RegisterBean(beanDefinitionList);
        registerBean.registerObj();
        map.putAll(registerBean.getCacheMap());

    }


    public static boolean needInit(  Annotation[] annotations){
        for (Annotation a:annotations
             ) {
            if(a instanceof Service){
                return true;
            }
        }
        return false;
    }


    // 对外提供获取实例对象的接口（根据id获取）
    public static  Object getBean(String id) {
        return map.get(id);
    }




    public static void main(String[] args) throws Exception {
        TransferServlet transferServlet = (TransferServlet)map.get("transferServlet");
        System.out.println(   transferServlet.getTransferServiceImpl());
        transferServlet.getTransferServiceImpl().transfer("1","1",100);

    }
}
